package stack;

import org.testng.annotations.Test;

import java.util.Stack;

public class Calculator {


    /**
     * 计算表达式的值
     *
     * @param expression 表达式 包含(,),+,-,*,/
     * @return
     */
    public static Double calculate(String expression) {

        Stack<String> opts = new Stack<>();
        Stack<Double> vals = new Stack<>();
        char[] chars = expression.toCharArray();
        for (char aChar : chars) {
            switch (aChar) {
                case '(':
                    break;
                case '+':
                case '-':
                case '*':
                case '/':
                    opts.push(String.valueOf(aChar));
                    break;
                case ')':
                    String op = opts.pop();
                    Double val = vals.pop();
                    switch (op) {
                        case "+":
                            val += vals.pop();
                            break;
                        case "-":
                            val = vals.pop() - val;
                            break;
                        case "*":
                            val *= vals.pop();
                            break;
                        case "/":
                            val = vals.pop() / val;
                            break;
                    }
                    vals.push(val);
                    break;
                default:
                    vals.push((double) (aChar - 48));
            }
        }
        return vals.pop();
    }

    @Test
    public void test() {

        System.out.println(calculate("(1+((2+3)*(4*5)))"));

    }
}
